#!/bin/bash

# EMS-CPP-V1 停止脚本：优雅结束后端程序，并确保 Web 端口释放

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info(){ echo -e "${BLUE}[INFO]${NC} $1"; }
log_warn(){ echo -e "${YELLOW}[WARN]${NC} $1"; }
log_success(){ echo -e "${GREEN}[OK]${NC} $1"; }
log_error(){ echo -e "${RED}[ERR]${NC} $1"; }

NAME="ems-cpp-v1"
WEB_PORT="9527"

# 杀进程函数（优雅 -> 强制）
kill_tree(){
  local pid="$1"
  if [ -z "$pid" ]; then return 0; fi
  if ! ps -p "$pid" >/dev/null 2>&1; then return 0; fi

  log_info "发送 SIGINT 到进程 $pid ($NAME)"
  kill -INT "$pid" 2>/dev/null || true
  for i in {1..20}; do
    if ! ps -p "$pid" >/dev/null 2>&1; then break; fi
    sleep 0.1
  done

  if ps -p "$pid" >/dev/null 2>&1; then
    log_warn "进程未退出，发送 SIGTERM"
    kill -TERM "$pid" 2>/dev/null || true
    sleep 1
  fi

  if ps -p "$pid" >/dev/null 2>&1; then
    log_warn "进程仍存活，发送 SIGKILL"
    kill -KILL "$pid" 2>/dev/null || true
  fi
}

# 1) 查找并结束 ems-cpp-v1 进程
PIDS=$(pgrep -f "/bin/${NAME}( |$)" || true)
if [ -z "$PIDS" ]; then
  log_warn "未发现 ${NAME} 进程"
else
  for p in $PIDS; do
    kill_tree "$p"
  done
  log_success "${NAME} 已停止"
fi

# 2) 确认 Web 端口占用情况
if command -v lsof >/dev/null 2>&1; then
  PORT_PIDS=$(lsof -ti :${WEB_PORT} || true)
elif command -v ss >/dev/null 2>&1; then
  PORT_PIDS=$(ss -lptn | awk -v p=":${WEB_PORT}" '$0~p{gsub(/pid=/,"");gsub(/,.*/,"");print $NF}' | awk -F\, '{print $1}' || true)
else
  PORT_PIDS=""
fi

if [ -n "$PORT_PIDS" ]; then
  # 仅结束名为 ems-cpp-v1 的占用者；其它程序只提示不强杀
  LEFT=""
  for p in $PORT_PIDS; do
    COMM=$(ps -o comm= -p "$p" 2>/dev/null || echo "")
    if echo "$COMM" | grep -q "${NAME}$"; then
      log_info "释放端口 ${WEB_PORT}：结束 ${NAME} (pid=$p)"
      kill_tree "$p"
    else
      LEFT+=" $p"
    fi
  done
  if [ -n "$LEFT" ]; then
    log_warn "端口 ${WEB_PORT} 仍被其它程序占用: ${LEFT}（未强制结束）"
    log_warn "可使用: lsof -i:${WEB_PORT} 查看并手动处理"
  else
    log_success "端口 ${WEB_PORT} 已释放"
  fi
else
  log_info "端口 ${WEB_PORT} 未被占用"
fi

exit 0

